import Config from './config'
import Directive from './directive'

const KEY_RE = /^[^\|]+/;
const COLON_MAP = /([^:]+):([^:]+)/;
const FILTER_RE = /\|[^\|]+/g;
const LOOP_RE = /(\w+)\s+(in)\s+(\w+)/;

function parseAttribute(attrName, attrValue) {

    if (attrName.indexOf(Config.prefix + '-') === -1) return null;
    const directiveName = attrName.slice(Config.prefix.length + 1);
    const valid = KEY_RE.test(attrValue);

    return directiveName && valid
        ? new Directive(directiveName, attrValue)
        : null;
}

function compile(el) {

    let vm = this;

    if (el.nodeType === 3) {
        return; //todo textCompile
    }

    [].forEach.call(el.attributes, attribute => {
        let attrValue = vm.forPrefix
            ? attribute.value.slice(vm.forPrefix.length + 1)
            : attribute.value;
        let directive = parseAttribute(attribute.name, attrValue);
        if(directive){
            directive.element = el
            directive.vm = vm
            directive.bind && directive.bind()
        }
    });

    //递归编译子元素
    if (el.childNodes && el.childNodes.length) {
        [].forEach.call(el.childNodes, child => {
            compile.call(vm, child);
        });
    }
}

export default {
    compile: compile
};